//
//  SYDSelectCityViewController.m
//  LantaiyuanBus
//
//  Created by lantaiyuan on 2017/2/6.
//  Copyright © 2017年 lantaiyuan. All rights reserved.

//  切换城市

#import "SYDSelectCityViewController.h"
#import "CustomTopView.h"

#import "LTYMineCell.h"
#define KMineCell @"LTYMineCell"
#import "BMChineseSort.h"

@interface SYDSelectCityViewController ()<CustomTopViewDelegate,UITableViewDelegate,UITableViewDataSource>
{
    NSMutableArray<cityListModel *> *dataArray;
}
@property(nonatomic,strong)UITableView *tableView;
//当前定位的城市
@property (nonatomic,copy)NSString *currentCityString;

/**排序后出现过的拼音首字母数组*/
@property (nonatomic,strong)NSMutableArray *indexArray;

/**排序好的结果数组*/
@property(nonatomic,strong)NSMutableArray *letterResultArr;

@end

@implementation SYDSelectCityViewController
#pragma mark---Lazy
-(UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, STATUS_AND_NAVIGATION_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT - STATUS_AND_NAVIGATION_HEIGHT) style:UITableViewStyleGrouped];
        _tableView.backgroundColor = CONTENT_BG_COLOR;
        _tableView.separatorColor = SEPARATE_LINE_COLOR;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.sectionIndexBackgroundColor = ClearColor;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.sectionIndexColor = TABBAR_COLOR;
        [self.view addSubview:_tableView];
    }
    return _tableView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initUI];
}
-(void)initUI{
    
    self.view.backgroundColor = CONTENT_BG_COLOR;
    self.navigationBar.title = @"选择地区";
    self.currentCityString = [YMSaveTool valueForKey:@"currentLocationName"];
    self.view.backgroundColor = CONTENT_BG_COLOR;
    [self.tableView registerNib:[UINib nibWithNibName:KMineCell bundle:nil] forCellReuseIdentifier:KMineCell];
    [self fetchCityListDataFromServer];
}
#pragma mark--- 获取城市信息
-(void)fetchCityListDataFromServer{
    [[SYDNetwork shareTool]getCityListWithVersion:[NSString getShortVersion] success:^(NSURLSessionDataTask *task, id responseObject) {
        @try {
            if ([responseObject[@"success"]boolValue] == 1) {
                [dataArray removeAllObjects];
                NSArray *stringsToSort = [cityListModel mj_objectArrayWithKeyValuesArray:responseObject[@"obj"]];
                //模拟网络请求接收到的数组对象 cityListModel数组
                dataArray = [[NSMutableArray alloc]initWithCapacity:0];
                for (NSInteger i = 0; i<stringsToSort.count; i++) {
                    cityListModel *cityM = [[cityListModel alloc]init];
                    cityM.cityname = [[stringsToSort objectAtIndex:i]valueForKey:@"cityname"];
                    cityM.citycode = [[stringsToSort objectAtIndex:i]valueForKey:@"citycode"];
                    cityM.number = i;
                    [dataArray addObject:cityM];
                }
            }else{//加载本地数据
                [self loadLocalCityListData];
            }
        } @catch (NSException *exception) {
            NSLog(@"--%@",exception.description);
        } @finally {
            
        }
        //根据Person对象的 name 属性 按中文 对 Person数组 排序
        self.indexArray = [BMChineseSort IndexWithArray:dataArray Key:@"cityname"];
        self.letterResultArr = [BMChineseSort sortObjectArray:dataArray Key:@"cityname"];
        [self.tableView reloadData];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"------%@",error.description);
        [self loadLocalCityListData];
    }];
}
-(void)loadLocalCityListData{
    [dataArray removeAllObjects];
    [self.indexArray removeAllObjects];
    [self.letterResultArr removeAllObjects];
    
    NSDictionary * dic = [NSString resourcePathWithFileName:@"cityListData.json"];
    NSArray *stringsToSort = [cityListModel mj_objectArrayWithKeyValuesArray:dic[@"obj"]];
    //模拟网络请求接收到的数组对象 cityListModel数组
    dataArray = [[NSMutableArray alloc]initWithCapacity:0];
    for (NSInteger i = 0; i<stringsToSort.count; i++) {
        cityListModel *cityM = [[cityListModel alloc]init];
        cityM.cityname = [[stringsToSort objectAtIndex:i]valueForKey:@"cityname"];
        cityM.citycode = [[stringsToSort objectAtIndex:i]valueForKey:@"citycode"];
        cityM.number = i;
        [dataArray addObject:cityM];
    }
    //根据Person对象的 name 属性 按中文 对 Person数组 排序
    self.indexArray = [BMChineseSort IndexWithArray:dataArray Key:@"cityname"];
    self.letterResultArr = [BMChineseSort sortObjectArray:dataArray Key:@"cityname"];
    [self.tableView reloadData];
}
#pragma mark --UITableViewDelegate

//section行数
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    NSLog(@"段数:%ld",self.indexArray.count + 1);
    return self.indexArray.count + 1;
    
}
//每一组section个数
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }else{
        NSArray *sectionArr = [self.letterResultArr objectAtIndex:section-1];
        return sectionArr.count;
    }
}
//section右侧index数组
-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView{
    return self.indexArray;
}
//点击右侧索引表项时调用 索引与section的对应关系
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index{
    return index;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return section == 0 ? 44 : 22;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if(section == 0){
        return 44;
    }
    return CGFLOAT_MIN ;
}
//返回每一段的段头
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return @"当前城市";
    }else{
        return [self.indexArray objectAtIndex:section-1];
    }
    
}
-(NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section{
    if (section == 0) {
        return @"全部地区";
    }
    return nil;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 0){
        LTYMineCell *cell = [tableView dequeueReusableCellWithIdentifier:KMineCell];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        if ([[YMSaveTool valueForKey:@"currentLocationName"]isEqualToString:@""]) {
            cell.titleLabel.text = @"定位失败";
        }else{
            cell.titleLabel.text = [NSString stringWithFormat:@"%@",[YMSaveTool valueForKey:@"currentLocationName"]];
        }
        cell.iconView.image = [UIImage imageNamed:@"icon_location"];
        cell.accessoryType = UITableViewCellAccessoryNone;
        return cell;
    }
    else
    {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        if(cell==nil)
        {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        }
        //获得对应的Person对象<替换为你自己的model对象>
        cityListModel *cityM = [[self.letterResultArr objectAtIndex:indexPath.section-1] objectAtIndex:indexPath.row];
        cell.textLabel.text = cityM.cityname;
        cell.textLabel.font = [UIFont systemFontOfSize:15];
        cell.textLabel.textColor = TITLE_COLOR;
        return cell;
    }
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    //获得对应的Person对象<替换为你自己的model对象>
    cityListModel *cityM = [[self.letterResultArr objectAtIndex:indexPath.section-1] objectAtIndex:indexPath.row];
    if (self.selectCityBlock) {
        //将自己的值传出去，完成传值
        self.selectCityBlock(cityM.cityname, cityM.citycode);
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}
-(void)tableView:(UITableView *)tableView willDisplayHeaderView:(nonnull UIView *)view forSection:(NSInteger)section{
    
    view.tintColor = [UIColor clearColor];
}
#pragma mark --CustomTopViewDelegate
-(void)didSelectBackButton
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

@end
